// const os = require('os');

import { Logger } from 'winston';
import { SQLiteManager} from './dbHelp';
const { exec } = require('child_process');

let logger = new Logger();

let sqliteManager = null ;

export class CommandExecutor {
  /**
   * 
   * @param {Logger} loggerF 
   * @param {SQLiteManager} dbManager 
   */
  constructor(loggerF, dbManager ) {
    // 可以在构造函数中初始化一些配置
    logger = loggerF;
    sqliteManager = dbManager;
  }


  /**
   * 
   * @param {string} command 
   * @param {Logger} logger 
   * @returns 
   */
  execShellCommand(command) {
    return new Promise((resolve, reject) => {
      exec(command, (error, stdout, stderr) => {
        if (error) {
          logger.info(`执行命令失败,msg: ${error.message},命令:${command}`);
          error.message = escapeHtml(error.message);
          sqliteManager.insert("INSERT INTO exec_info_table (job_command, execution_result) VALUES ('" + command + "', '" + error.message + "');")
          reject(error);
        } else {
          let res = stdout;
          if(stderr){
              res = stderr;
          }
          logger.info(`执行命令成功,命令:${command}`);
          res = escapeHtml(res);
          sqliteManager.insert("INSERT INTO exec_info_table (job_command, execution_result) VALUES ('" + command + "', '" + res + "');")
          resolve(stdout);
        }
    });
  });
  }



}

function escapeHtml(str) {
  return str.replace(/'/g, '&apos;').replace(/"/g, '&quot;');
}

// CommandExecutor.execShellCommand('ps aux').then(({ stdout, stderr }) => console.log(stdout, stderr)).catch((err) => console.error(err));
// paths = os.homedir();
// console.log(paths + '/wumaapp/app.log')
// CommandExecutor.execShellCommand('cat ' + paths + '/wumaapp/app.log').then(({ stdout, stderr }) => console.log(stdout, stderr)).catch((err) => console.error(err));